<template>
  <div>
    <el-tree
      ref="layerTree"
      :data="treeData"
      show-checkbox
      node-key="pkid"
      :props="defaultProps"
      default-expand-all
      @check="handleCheck"
      @node-click="handleNodeClick"
      :filter-node-method="filterNode"
    >
      <!--      :default-checked-keys='defaultCheckedKeys'-->
      <div
        slot-scope="{ node, data }"
        style="color: white; display: flex"
      >
        <icon
          v-if="data.catalogName"
          :title="'文件夹'"
          :name="folderIcon(data)"
          :color="'#A7BECA'"
        />
        <icon
          v-if="data.sourceName"
          :title="'数据服务'"
          :name="'shujufuwu'"
          :color="'#A7BECA'"
        />
        <span
          v-if="data.sourceName"
          @click="handleCheck"
          class="margin"
          >{{ data.sourceName }}</span
        >
        <!--        <span v-if='data.sourceName' class='margin'>{{ data.sourceName.length>8?data.sourceName.slice(0,8)+'...': data.sourceName}}</span>-->
        <span v-if="data.catalogName" class="margin">{{
          data.catalogName
        }}</span>
        <!--        {{ data.sourceName ? data.sourceName : data.catalogName }}-->
      </div>
    </el-tree>
  </div>
  <!--  :props="defaultProps"-->
  <!--  @check="handleCheck"-->
</template>

<script>
import { treeByTypeId } from '@/api/tree'
import { getAction } from '@/utils/helper'
import Icon from '@/components/icon/index'
import { retrieveDataServiceById } from '@/api/multiple-dataservice'
import New from '@/utils/new'

export default {
  name: 'DecisionTree',
  components: {
    Icon
  },
  props: {
    treeTypeName: {
      type: String,
      default: ''
    },
    viewerId: {
      type: String,
      default: ''
    },
    filter: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 树组件相关
      // treeData: [
      //   {
      //     pkid: '1',
      //     parentId: '-1',
      //     catalogName: '现状',
      //     children: [
      //       {
      //         pkid: '1-1',
      //         parentId: '1',
      //         sourceName: '现状1'
      //       },
      //       {
      //         pkid: '1-2',
      //         parentId: '1',
      //         sourceName: '现状2'
      //       },
      //       {
      //         pkid: '1-3',
      //         parentId: '1',
      //         catalogName: '现状子目录',
      //         children: [
      //           {
      //             pkid: '1-3-1',
      //             parentId: '1-3',
      //             sourceName: '子目录服务'
      //           }
      //         ]
      //       }
      //     ]
      //   },
      //   {
      //     pkid: '2',
      //     parentId: '-1',
      //     catalogName: '规划'
      //   },
      //   {
      //     pkid: '3',
      //     parentId: '-1',
      //     catalogName: 'BIM'
      //   }
      // ],
      treeData: [],
      defaultProps: {
        children: 'children'
        // label: 'catalogName'
        // disabled: (_data, node) => {
        //   return this.loadingList.includes(node.key)
        // }
      },
      // 默认加载的图层列表
      defaultCheckedKeys: [],
      // 上一次加载的图层树节点列表
      lastCheckedNodes: [],
      // 正在加载的图层id数组
      loadingList: []
    }
  },
  watch: {
    filter: {
      handler(value) {
        this.$refs.layerTree.filter(value)
      }
    }
  },
  async created() {
    const { layerManager } = await getAction(this.viewerId)
    this.layerManager = layerManager
    // 已加载图层赋值
    this.layerManager.layers.forEach((item) => {
      this.defaultCheckedKeys.push(item.id)
    })
    this.$refs.layerTree.setCheckedKeys(
      this.defaultCheckedKeys
    )
    // console.log('默认选中', this.defaultCheckedKeys)
    // 监听添加删除
    this.layerManager.on('add', ({ id }) => {
      this.loadingList = this.loadingList.filter(
        (item) => item !== id
      )
    })
    this.layerManager.on('del', (id) => {
      this.$nextTick(() => {
        if (this.$refs.layerTree) {
          this.$refs.layerTree.setChecked(id, false)
        }
        this.lastCheckedNodes =
          this.lastCheckedNodes.filter((item) => {
            return item.pkid !== id
          })
      })
    })
    this.getTreeData('5')
    // this.getTreeData('2')
    // this.getTreeData('3')
  },
  methods: {
    folderIcon(node) {
      switch (node.pkid) {
        case '1':
          return 'xianzhuang'
        case '2':
          return 'guihua'
        case '3':
          return 'bim'
        default:
          return 'wenjianjia'
      }
    },
    getTreeData(type) {
      treeByTypeId(type).then(async (res) => {
        if (res.success) {
          this.treeData = res.data[0].children
          this.addResourceInfo(this.treeData)

          // 默认加载第一个服务
          // const defaultService =
          //   await this.findDefaultAddService()
          // if (defaultService) {
          //   defaultService.dataList =
          //     await this.getDataList(defaultService.pkid)
          //   if (defaultService.serviceType === '27') {
          //     defaultService.serviceUrl =
          //       defaultService.dataList[0].serviceUrl
          //     defaultService.signService =
          //       defaultService.dataList[0].signService
          //     defaultService.currentDataIndex = 0
          //     this.layerManager.add(defaultService)
          //   } else {
          //     defaultService.serviceUrl =
          //       defaultService.dataList[0].serviceUrl
          //     defaultService.signService =
          //       defaultService.dataList[0].signService
          //     defaultService.currentDataIndex = 0
          //     this.layerManager.add(defaultService)
          //   }
          //   New.$emit('openTreeDataList', [
          //     defaultService,
          //     this.viewerId
          //   ])
          // }
          // const find = this.treeData.find(
          //   (item) => item.pkid === type
          // )
          // if (find) {
          //   find.children = res.data[0].children
          //   this.addResourceInfo(find.children)
          // }
        }
      })
    },
    addResourceInfo(data) {
      data.forEach((item) => {
        if (item.resourceInfo) {
          item.children = item.children.concat(
            item.resourceInfo
          )
        }
        if (item.children && item.children.length) {
          this.addResourceInfo(item.children)
        }
      })
    },
    // 找到默认加载的服务
    findDefaultAddService() {
      return new Promise((resolve) => {
        for (const a of this.treeData) {
          for (const b of a.children) {
            if (b.serviceType) {
              resolve(b)
            } else {
              for (const c of b.children) {
                if (c.serviceType) {
                  resolve(c)
                }
              }
            }
          }
        }
      })
    },
    // 获取服务的地图服务列表
    async getDataList(pkid) {
      const list = []
      await retrieveDataServiceById({
        pageIndex: 1,
        pageSize: 999,
        serviceId: pkid
      }).then((res) => {
        if (res.success) {
          if (res.data && res.data.length) {
            // 将配置的数据列表赋给原始数据
            list.push(...res.data)
          } else {
            this.$message.warning('该服务未配置数据')
          }
        } else {
          this.$message.error(
            res.message || '服务数据查询失败'
          )
        }
      })
      return list
    },
    handleCheck(_currentNode, checkedNodes) {
      // 开始处理增加和移除的图层
      console.log('_currentNode ', _currentNode)
      console.log('checkedNodes', checkedNodes)
      // debugger
      this.$emit(
        'handleCheckList',
        checkedNodes.checkedNodes.filter((item) => {
          return item.sourceName
        }),
        _currentNode
      )
      if (!_currentNode.sourceName) {
        this.$emit('handleCheck', false)
        // return
      }
      const newArr = checkedNodes.checkedNodes.filter(
        (item) => !item.children
      )
      console.log('newArr', newArr)
      if (newArr.length === 0) {
        // 没有一条选中数据时关闭右侧echarts
        this.$emit('handleCheck', false)
        // return
      }
      const oldArr = [...this.lastCheckedNodes]
      // if (oldArr.length === 0 && this.defaultCheckedKeys.length > 0) {
      //   this.defaultCheckedKeys.forEach((key) => {
      //     oldArr.push(this.$refs.layerTree.getNode(key).data)
      //   })
      //   console.log('重新赋值', oldArr)
      // }
      // console.log('oldArr', oldArr)
      newArr.forEach(async (newItem) => {
        const index = oldArr.findIndex(
          (oldItem) => oldItem.pkid === newItem.pkid
        )
        if (index > -1) {
          // 取消选中时关闭右侧echarts
          this.$emit('handleCheck', false)
          oldArr.splice(index, 1)
        } else {
          this.$emit('handleCheck', true)
          // const { pkid, type, height = 0 } = newItem
          // 加载开始 禁用子节点
          this.loadingList.push(newItem.pkid)
          // this.layerManager.add({
          //   ...newItem,
          //   // type: this.$store.state.tree.treeTypeId[type],
          //   type: type,
          //   data: newItem.serviceUrl || '',
          //   height,
          //   onClick: ({ entity, position, title }) => {
          //     console.log(entity, position, title)
          //   }
          // })
          const parent = this.treeData.find(
            (item) => item.pkid === newItem.catalogId
          )
          if (parent) {
            newItem.from = parent.type
          }
          if (!newItem.dataList) {
            newItem.dataList = await this.getDataList(
              newItem.pkid
            )
          }
          if (newItem.serviceType === '27') {
            newItem.serviceUrl =
              newItem.dataList[0].serviceUrl
            newItem.signService =
              newItem.dataList[0].signService
            newItem.currentDataIndex = 0
            this.layerManager.add(newItem)
          } else {
            newItem.serviceUrl =
              newItem.dataList[0].serviceUrl
            newItem.signService =
              newItem.dataList[0].signService
            newItem.currentDataIndex = 0
            this.layerManager.add(newItem)
          }
          New.$emit('openTreeDataList', [
            newItem,
            this.viewerId
          ])
          // if (newItem.serviceUrl.indexOf('[{') !== -1) {
          //   newItem.serviceUrl = JSON.parse(
          //     newItem.serviceUrl
          //   )[0].serviceUrl
          //   this.layerManager.add(newItem)
          // } else {
          //   this.layerManager.add(newItem)
          // }
        }
      })
      oldArr.forEach((oldItem) => {
        this.layerManager.del(oldItem.pkid)
        New.$emit('closeTreeDataList', [
          oldItem.pkid,
          this.viewerId
        ])
      })
      this.lastCheckedNodes = newArr
      this.$emit('checkedData', newArr)
      // console.log('=======')
      // console.log('newArr', newArr)
      // console.log('oldArr', oldArr)
      // console.log('lastCheckedNodes', this.lastCheckedNodes)
    },
    handleNodeClick(data, node, el) {
      this.$emit('handleNodeClick', data, node, el)
    },
    filterNode(value, data) {
      console.log('filterNode', value, data)
      if (!value) return true
      if (data.sourceName) {
        return data.sourceName.indexOf(value) !== -1
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-tree-node__content {
    .el-checkbox {
      margin-right: 5px !important;
    }

    & > div {
      width: 100%;
      overflow: hidden;

      .margin {
        margin-left: 5px;
        display: inline-block;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
